#!/usr/bin/python
import cgi
import cgitb
import os
from pygallib import usersession
from pygallib import layoutlib
from pygallib import albumlib
from pygallib import userlib
from pygallib import picturelib

# Enable debug print
cgitb.enable()

# Pre-processing
logged_in = usersession.logged_in()

# Printing Headers
headers = {}
headers["Content-type"] = "text/html"
layoutlib.print_http_headers(headers)
layoutlib.print_page_open("PyGallery - Home")
print("<body>")
menu = []
menu.append(("Home", "gallery.cgi"))

session_user = None
if logged_in:
  session_user = usersession.get_session_user()

layoutlib.print_page_header(menu, session_user)
print('<div id="page_body">')

# Get the fields from url
fields = cgi.FieldStorage()

# Get the id of the album and user
user_authorized = False
if "id" in fields:
  album_id = int(fields["id"].value)
  # Get album information
  album = albumlib.get_album(album_id)
  # Get user who created album
  user = userlib.get_user_by_id(album["user_id"])
  if logged_in:
    if (session_user["user_id"] == user["user_id"] or 
        session_user["root"] == 1):
      user_authorized = True

# If they uploaded an image, there will be a picture tag
if user_authorized:
  form_errors = []
  if "picture" in fields:
    picture = fields["picture"]
    label = fields["label"].value
    if len(label) == 0:
      label = picture.filename
    if picture.file:
      # Save normal size
      f = open(os.environ["DOCUMENT_ROOT"]
          + "/PictureShare/users/"
          + user["username"] + "/"
          + "album"+ str(album["album_id"]) + "/"
          + picture.filename , "w")
      f.write(picture.file.read())    
      f.close()
      # Save thumbnail
      f = open(os.environ["DOCUMENT_ROOT"]
          + "/PictureShare/users/"
          + user["username"] + "/"
          + "albumthumb"+ str(album["album_id"]) + "/"
          + picture.filename , "w")
      picture.file.seek(0)
      f.write(picture.file.read())
      f.close()
      # Insert into DB
      picturelib.add_picture(album["album_id"], 
          user["user_id"], 
          picture.filename, 
          label)
      print("Upload Successful!")

  for error in form_errors:
    print('<p>%s</p>' % error)

  # They are going to upload, printing upload form
  print("""Upload an image to album: <a href="album.cgi?id=%d">%s</a>""" 
      % (album_id, album["name"]))
  print("""
  <form action="album_picture_add.cgi" 
    method="post" enctype="multipart/form-data">
    <ul>
      <input type="hidden" name="id" value="%d" />
      <li>
        <label for="picture">Picture:</label>
        <input name="picture" type="file" />
      </li>
      <li>
        <label for="label">Caption: (10 character limit)</label> 
        <input type="text" maxlength="10" name="label" size="30"/>
      </li>
      <li>
        <input type="submit" value="Submit" />
      </li>
    </ul>
  </form>
  """ % (album_id))
elif "id" not in fields:
  print('<p>Please select an album from <a href="gallery.cgi">here</a>.</p>')
else:
  print("<p>You are not authorized to do that.</p>")

print('</div>')
layoutlib.print_page_close()
